const { log } = require("../utils");
const configLang = require("../configLang");
const t = require("../../config/dict");
const path = require("path");
const fs = require("fs");
const configPWA = require("../configPWA");
const next = (context) => {
  configPWA(context, true);
};

module.exports = (packageName, options) => {
  let { to } = options || {};
  configLang({ lang: "english" }, (context) => {
    if (!to) {
      to = packageName;
    }
    const dirPath = path.resolve(process.cwd(), to);
    const filePath = dirPath + "/package.json";
    if (fs.existsSync(dirPath) && fs.existsSync(filePath)) {
      let pkg = fs.readFileSync(
        path.resolve(process.cwd(), to + "/package.json"),
        "utf-8"
      );
      pkg = JSON.parse(pkg);
      let projectEnv = ["webpack"];
      for (let n in pkg) {
        for (let x in pkg[n]) {
          projectEnv = [
            ...projectEnv,
            ...["webpack", "vite"].filter((item) => x.toLowerCase() === item),
          ];
        }
      }
      context.name = pkg.name;
      context.metadata = {
        projectDir: to,
        projectVersion: pkg.version,
        projectType: projectEnv,
      };
      next(context);
    } else {
      log("error", {
        message: [
          t(context.lang, "初始化"),
          t(context.lang, "失败"),
          t(context.lang, "。"),
        ].join(" "),
      });
    }
  });
};
